package com.yunchang.springboot;

import com.amazonservices.mws.client.MwsUtl;
import com.yunchang.springboot.mapper.ATestMapper;
import com.yunchang.springboot.mapper.base.FinanceShopSkuMapper;
import com.yunchang.springboot.mapper.basic.IBaseErpskuSkuRelationMapper;
import com.yunchang.springboot.mapper.basic.IBaseSkuInfoMapper;
import com.yunchang.springboot.mapper.caravan.CaravanMskuDataMapper;
import com.yunchang.springboot.mapper.caravan.CaravanStorageLogDataMapper;
import com.yunchang.springboot.mapper.mws.finances.MwsFinancesFinancialReportMapper;
import com.yunchang.springboot.mapper.shop.ProfileMapper;
import com.yunchang.springboot.mapper.shop.ShopMapper;
import com.yunchang.springboot.models.DO.CaravanMskuData;
import com.yunchang.springboot.models.DO.CaravanStorageLogData;
import com.yunchang.springboot.models.DO.basic.BaseErpskuSkuRelationDTO;
import com.yunchang.springboot.models.DO.basic.BaseSkuInfoDTO;
import com.yunchang.springboot.models.base.FinanceShopSku;
import com.yunchang.springboot.scheduled.MWS.MwsFinancesEventReportSchedule;
import com.yunchang.springboot.scheduled.MWS.MwsOrderSchedule;
import com.yunchang.springboot.scheduled.amazonAdvert.AmazonAdvBrandsDataSchedule;
import com.yunchang.springboot.scheduled.amazonAdvert.AmazonAdvErrorDateSchedule;
import com.yunchang.springboot.scheduled.caravanapi.CaravanApiSchedule;
import com.yunchang.springboot.scheduled.finance.FinanceAccountsSettlementSchedule;
import com.yunchang.springboot.scheduled.finance.FinanceCaravanDebitCreditSchedule;
import com.yunchang.springboot.service.AmazonAdvert.AmazonAdvertBrandsReportDataProcessingService;
import com.yunchang.springboot.service.aTest.ATestService;
import com.yunchang.springboot.utils.DateUtil;
import lombok.extern.slf4j.Slf4j;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import com.yunchang.springboot.base.BaseService;

import javax.annotation.Resource;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.XMLGregorianCalendar;
import java.math.BigDecimal;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.WeekFields;
import java.util.*;


@Slf4j
@RunWith(SpringRunner.class)
@SpringBootTest
public class test extends BaseService {
    @Autowired
    CaravanApiSchedule caravanApiSchedule;
    @Autowired
    AmazonAdvBrandsDataSchedule brandsDataSchedule;
    @Autowired
    AmazonAdvertBrandsReportDataProcessingService amazonAdvertBrandsReportDataProcessingService;
    @Autowired
    ProfileMapper profileMapper;
    @Autowired
    AmazonAdvErrorDateSchedule amazonAdvErrorDateSchedule;
    @Autowired
    CaravanStorageLogDataMapper storageLogDataMapper;
    @Autowired
    MwsOrderSchedule mwsOrderSchedule;
    @Autowired
    ShopMapper shopMapper;
    @Autowired
    FinanceCaravanDebitCreditSchedule financeCaravanDebitCreditSchedule;
    @Autowired
    ATestMapper aTestMapper;
    @Autowired
    ATestService aTestService;
    @Autowired
    MwsFinancesEventReportSchedule mwsFinancesEventReportSchedule;
    @Resource
    MwsFinancesFinancialReportMapper mwsFinancesFinancialReportMapper;
    @Resource
    FinanceAccountsSettlementSchedule financeAccountsSettlementSchedule;
    @Autowired
    IBaseErpskuSkuRelationMapper iBaseErpskuSkuRelationMapper;
    @Autowired
    FinanceShopSkuMapper financeShopSkuMapper;
    @Autowired
    CaravanMskuDataMapper caravanMskuDataMapper;
    @Autowired
    IBaseSkuInfoMapper iBaseSkuInfoMapper;

    @Test
    public void getData() {
        WeekFields weekFields = WeekFields.of(DayOfWeek.SUNDAY, 1);
        //2018年第一天
        System.out.println(LocalDateTime.of(2021, 1, 1, 0, 0, 0).get(weekFields.weekOfYear()));
        //2018年最后一天
        System.out.println(LocalDateTime.of(2018, 12, 31, 0, 0, 0).get(weekFields.weekOfYear()));
        //2019年第一天
        System.out.println(LocalDateTime.of(2021, 1, 2, 0, 0, 0).get(weekFields.weekOfYear()));
        //2019年最后一天
        System.out.println(LocalDateTime.of(2019, 12, 31, 0, 0, 0).get(weekFields.weekOfYear()));
        //这天是星期六
        System.out.println(LocalDateTime.of(2019, 4, 6, 0, 0, 0).get(weekFields.weekOfYear()));
        //这天是星期日
        System.out.println(LocalDateTime.of(2019, 4, 7, 0, 0, 0).get(weekFields.weekOfYear()));
        //这天是星期一
        System.out.println(LocalDateTime.of(2019, 4, 8, 0, 0, 0).get(weekFields.weekOfYear()));
        System.out.println(LocalDateTime.now().get(weekFields.weekOfYear()));
    }

    @Test
    public void caravanTest() throws InterruptedException {
//        "库存查询","出入库流水","采购单","订单列表","收付款单","商品查询","MSKU列表","账户日志","补货计划","调拨发货"

        String[] taskNames = {"MSKU列表"};
        LocalDate localDate = LocalDate.now();
        int day = localDate.getDayOfYear();
        for (int i = 0; i < taskNames.length; i++) {
            String taskName = taskNames[i];
            for (int j = day - 1; j > 0; j--) {
                String start = localDate.minusDays(j).format(DateTimeFormatter.ofPattern("yyyy-MM-dd")) + " 00:00:00";
                String end = localDate.minusDays(j).format(DateTimeFormatter.ofPattern("yyyy-MM-dd")) + " 23:59:59";
                caravanApiSchedule.baseHandle(taskName, start, end);
                Thread.sleep(100l);
            }
        }
//        String[] taskNames = {"库存查询","订单列表","商品查询","MSKU列表","账户日志","补货计划","调拨发货"};//,"收付款单","采购单","出入库流水","商品查询"
//        LocalDate localDate = LocalDate.of(2019,12,31);
//        int day = localDate.getDayOfYear();
//        for (int j = 30; j >= 0; j--) {
//            for (int i = 0; i < taskNames.length; i++) {
//                String taskName = taskNames[i];
//                String start = localDate.minusDays(j).format(DateTimeFormatter.ofPattern("yyyy-MM-dd")) + " 00:00:00";
//                String end = localDate.minusDays(j).format(DateTimeFormatter.ofPattern("yyyy-MM-dd")) + " 23:59:59";
//                System.out.println(start + "  " + end);
//                caravanApiSchedule.baseHandle(taskName, start, end);
//                Thread.sleep(200l);
//            }
//        }

//        String[] taskNames2 = {"商品查询"};
//        System.out.println(localDate.toString());
//        for (int j = 0; j < 365 * 3; j++) {
//            for (int i = 0; i < taskNames2.length; i++) {
//                String taskName = taskNames2[i];
//                String start = localDate.minusDays(j).format(DateTimeFormatter.ofPattern("yyyy-MM-dd")) + " 00:00:00";
//                String end = localDate.minusDays(j).format(DateTimeFormatter.ofPattern("yyyy-MM-dd")) + " 23:59:59";
//                caravanApiSchedule.baseHandle(taskName, start, end);
//                Thread.sleep(200l);
//            }
//        }
    }

//    @Test
//    public void brandsTest() {
//        //brandsDataSchedule.addYesterdayAdvBrandsCampaignsReport();
//        LocalDateTime localDateTime = LocalDateTime.now();
//        String date;
//        List<ShopAreaProfile> shopAreaProfileList = profileMapper.getAllDatas();
//        for (ShopAreaProfile shopAreaProfile : shopAreaProfileList) {
//            if (shopAreaProfile.getShopId() == 23) {
//                for (int i = 30; i <= 60; i++) {
//                    date = localDateTime.minusDays((long) i).format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
//                    amazonAdvertBrandsReportDataProcessingService.addOriginalDataAdvBrandsCampaignsReport(date, shopAreaProfile);
//                    System.out.println("店铺id：" + shopAreaProfile.getShopId() + "的BrandsCampaignsReport添加" + (1) + "次");
//                    amazonAdvertBrandsReportDataProcessingService.addOriginalDataAdvBrandsAdGroupsReport(date, shopAreaProfile);
//                    System.out.println("店铺id：" + shopAreaProfile.getShopId() + "的BrandsAdGroupsReport添加" + (1) + "次");
//                    amazonAdvertBrandsReportDataProcessingService.addOriginalDataAdvBrandsKeywordsReport(date, shopAreaProfile);
//                    System.out.println("店铺id：" + shopAreaProfile.getShopId() + "的BrandsKeywordsReport添加" + (1) + "次");
//                    amazonAdvertBrandsReportDataProcessingService.addOriginalDataAdvBrandsTargetsReport(date, shopAreaProfile);
//                    System.out.println("店铺id：" + shopAreaProfile.getShopId() + "的BrandsTargetsReport添加" + (1) + "次");
//                    amazonAdvertBrandsReportDataProcessingService.addOriginalDataAdvBrandsSearchTermReport(date, shopAreaProfile);
//                    System.out.println("店铺id：" + shopAreaProfile.getShopId() + "的BrandsSearchTermReport添加" + (1) + "次");
//                    log.info("-----------------------店铺id：" + shopAreaProfile.getShopId() + "和区域id:" + shopAreaProfile.getAreaId() + "和配置文件id:" + shopAreaProfile.getProfileId() + "获取" + date + "的品牌相关报表数据任务完成-------------------------------");
//                }
//            }
//        }
//        System.out.println("成功结束");
//    }

    @Test
    public void aaasd() {
        //amazonAdvErrorDateSchedule.addErrorDate();
        brandsDataSchedule.reAddAdvertErrorDateData();
        //brandsDataSchedule.addLastMonthAdvBrandsReport();
    }

    @Test
    public void caravantest() {
        String logId = "323";
        CaravanStorageLogData oneInfo = storageLogDataMapper.getOneInfoByLogId(logId);
        System.out.println(null == oneInfo);
        if (null == oneInfo && null == oneInfo.getId()) {
            System.out.println(oneInfo.getId());
        }
    }

    @Test
    public void stringTest() {
        String content = "[7e23ed4808611cff]退货单验货入库<input type=\"hidden\" value=\"62421400\"/>";
//        // <p>段落替换为换行
//        content = content.replaceAll("<p .*?>", "\r\n");
//        // <br><br/>替换为换行
//        content = content.replaceAll("<br\\s*/?>", "\r\n");
//        // 去掉其它的<>之间的东西
//        content = content.replaceAll("\\<.*?>", "");
//        content = content.replaceAll("\\[.*?]", "");
//        // 去掉空格
//        content = content.replaceAll(" ", "");
        content = content.replaceAll("\\[", "");
        int idx = content.indexOf("]");
        content = content.substring(0, idx);
        System.out.println(content);

    }

    @Test
    public void dsssss() {
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String timeCreate = "2020-04-21 09:10:46";
        LocalDateTime createTime = LocalDateTime.parse(timeCreate, df);
        int year = createTime.getYear();
        int month = createTime.getMonthValue();
        System.out.println(year + " " + month);
        String time = LocalDateTime.of(createTime.getYear(), createTime.getMonthValue(), 1, 0, 0, 0).format(df);
        System.out.println(time);
    }

    @Test
    public void ces() {
        int preSkuNum = 1;
        int purchaseNum = 1;
        BigDecimal preAmount = BigDecimal.valueOf(4);
        BigDecimal amount = BigDecimal.valueOf(4);
        if (!(preSkuNum == purchaseNum && preAmount.compareTo(amount) == 0)) {
            System.out.println(1111);
        }
    }

    @Test
    public void mwsOrderTest() throws DatatypeConfigurationException {
        mwsOrderSchedule.GetListOrdersAsync();
    }

    @Test
    public void adas() {
        XMLGregorianCalendar lastUpdatedBefore = MwsUtl.getDTF().newXMLGregorianCalendar();
        lastUpdatedBefore.setYear(2020);
        lastUpdatedBefore.setMonth(2);
        lastUpdatedBefore.setDay(3);
        lastUpdatedBefore.setTime(0, 0, 0);
        System.out.println(lastUpdatedBefore.toString());
    }

    @Test
    public void financeDataTest() {
        log.info("-------------------------------开始出入库流水的财务数据----------------------------------");
        financeCaravanDebitCreditSchedule.calculateStorageLogData();
//        log.info("-------------------------------开始采购单的财务数据----------------------------------");
//        financeCaravanDebitCreditSchedule.calculatePurchaseData();
//        log.info("-------------------------------开始账单的财务数据----------------------------------");
//        financeCaravanDebitCreditSchedule.calculateBillsData();
//        log.info("-------------------------------开始分摊运费的财务数据----------------------------------");
//        financeCaravanDebitCreditSchedule.calculateAllocatedFreight();
    }

    @Test
    public void asdasd() {
        //aTestService.test();
        financeCaravanDebitCreditSchedule.dataTest();
    }

    @Test
    public void mwsFinancesTest() {
        LocalDate localDate = LocalDate.now().minusDays(2);
        LocalDateTime localDateTime = LocalDateTime.of(localDate.getYear(), localDate.getMonth(), localDate.getDayOfMonth(), 0, 0, 0);
        int day = localDateTime.getDayOfYear();
        for (int j = day - 1; j > 0; j--) {
            LocalDateTime start = localDateTime.minusDays(j);
            LocalDateTime end = localDateTime.minusDays(j - 1).minusSeconds(1);
            //System.out.println("开始：" + start + "，结束：" + end);
            mwsFinancesEventReportSchedule.getFinancesDataList(start, end);
        }
    }

    @Test
    public void setNullTest() {
        String documentNum = "1090014569";
        String purchaseId = documentNum.substring(documentNum.length() - 5);
        System.out.println(purchaseId);
    }

    @Test
    public void uuId() {
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime nowTime = LocalDateTime.now();
        String latestDate = "2020-02-03 12:12:12";
        LocalDateTime startTime;
        if (latestDate == null || "".equals(latestDate)) {
            startTime = LocalDateTime.of(nowTime.getYear(), nowTime.getMonthValue(), nowTime.getDayOfMonth() - 2, 0, 0, 0);
        } else {
            startTime = LocalDateTime.parse(latestDate, df).minusSeconds(-1);
        }
        LocalDateTime endTime = LocalDateTime.of(nowTime.getYear(), nowTime.getMonthValue(), nowTime.getDayOfMonth() - 2, 23, 59, 59);
        log.info("开始" + startTime + "到" + endTime + "的马帮accountData数据拉取任务");
        System.out.println(startTime.format(df) + "  " + endTime.format(df));
    }

    @Test
    public void accountSettlementTest() {
        int year = 2020;
        for (int i = 1; i < 6; i++) {
            int month = i;
            String period;
            if (month < 10) {
                period = year + "-0" + i;
            } else {
                period = year + "-" + i;
            }
            financeAccountsSettlementSchedule.confirmAccountSettlement(period);
        }
    }

    @Test
    public void mskuTest() {
        String fetureDate = DateUtil.getFetureDate(0);
        List<CaravanMskuData> allList = caravanMskuDataMapper.getAllList();
        for (CaravanMskuData caravanMskuData : allList) {
            String msku = caravanMskuData.getMsku();
            String stockSku = caravanMskuData.getStockSku();
            //根据stockSku去finance_shop_sku表中获得对应的sellerId和area
            FinanceShopSku infoBySku = financeShopSkuMapper.getInfoBySku(stockSku);
            if (null != infoBySku) {
                String sellerId = infoBySku.getSellerId();
                String area = infoBySku.getArea();
                //根据sellerId和area和msku去base_sku_info表中拿到这个msku对应的id
                Integer mskuId = iBaseSkuInfoMapper.getIdByMskuAndSellerIdAndArea(msku, sellerId, area);
                //如果没有这个id，表示这个店铺、这个区域下没有这个msku，新增
                if (mskuId == null) {
                    BaseSkuInfoDTO baseSkuInfoDTO = new BaseSkuInfoDTO();
                    baseSkuInfoDTO.setSellerId(sellerId);
                    baseSkuInfoDTO.setArea(area);
                    baseSkuInfoDTO.setSku(msku);
                    baseSkuInfoDTO.setParentSku("");
                    baseSkuInfoDTO.setCategory("");
                    baseSkuInfoDTO.setAddUser("sujiandong");
                    baseSkuInfoDTO.setAddTime(fetureDate);
                    baseSkuInfoDTO.setModUser("sujiandong");
                    baseSkuInfoDTO.setModTime(fetureDate);
                    iBaseSkuInfoMapper.insert(baseSkuInfoDTO);
                    mskuId = iBaseSkuInfoMapper.getIdByMskuAndSellerIdAndArea(msku, sellerId, area);
                }
                BaseSkuInfoDTO oneInfoBySkuAndErpSku = iBaseErpskuSkuRelationMapper.getOneInfoBySkuAndErpSku(mskuId, stockSku);
                if (oneInfoBySkuAndErpSku == null) {
                    BaseErpskuSkuRelationDTO baseErpskuSkuRelationDTO = new BaseErpskuSkuRelationDTO();
                    baseErpskuSkuRelationDTO.setErpsku(stockSku);
                    baseErpskuSkuRelationDTO.setSku(mskuId);
                    baseErpskuSkuRelationDTO.setAddUser("sujiandong");
                    baseErpskuSkuRelationDTO.setAddTime(fetureDate);
                    baseErpskuSkuRelationDTO.setModUser("sujiandong");
                    baseErpskuSkuRelationDTO.setModTime(fetureDate);
                    iBaseErpskuSkuRelationMapper.insert(baseErpskuSkuRelationDTO);
                }
            }

        }
    }
}
